package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: hwq
 * @Date: 2020/1/8 15:50
 * @Version 1.0
 */
@Service
public class RedisCacheService {
    private static final String HASH_KEY_VO = "redis_cache_vo";
    private static final String HASH_KEY_LIST = "redis_cache_list";
    @Autowired
    private RedisClient redisClient;

    /**
     * 查询缓存
     *
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T selectByKey(String key, Class<T> clazz) {
        String str = redisClient.hget(HASH_KEY_VO, key);
        if (str != null) {
            return JSON.parseObject(str, clazz);
        }
        return null;
    }
    public <T> List<T> selectListByKey(String key, Class<T> clazz) {
        String str = redisClient.hget(HASH_KEY_LIST, key);
        if (str != null) {
            return JSON.parseArray(str, clazz);
        }
        return null;
    }

    /**
     * 添加缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean addCacheByKey(String key, String value) {
        redisClient.hset(HASH_KEY_VO, key, value);
        return true;
    } /**
     * 添加缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean addCacheListByKey(String key, String value) {
        redisClient.hset(HASH_KEY_LIST, key, value);
        return true;
    }

    /**
     * 删除缓存
     * @param key
     * @return
     */
    public boolean delCache(String key) {
        redisClient.del(HASH_KEY_LIST);
        redisClient.del(HASH_KEY_VO);
        return true;
    }
}
